package com.zone.core.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.zone.core.BR
import com.zone.core.contract.OnEventListener
import com.zone.core.ext.back
import com.zone.core.ext.bind
import com.zone.core.model.EVENT_BACK
import javax.inject.Inject


/**
 *Author: last
 *Time: 2019-09-03
 *Description: xxx
 */
abstract class BaseBindingViewModelFragment<BINDING : ViewDataBinding, VM : BaseViewModel> :
    BaseBindingFragment<BINDING>(), OnEventListener {

    lateinit var binding: BINDING

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    val viewModel: VM by lazy {
        createViewModel()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        inject()
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        createViewModel()
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    private fun createViewModel(): VM {
        val vm = getViewModelType(javaClass)?.let {
            ViewModelProvider(this,viewModelFactory)[it] as VM
        }
        vm!!.bind(this)
        return vm
    }

    override fun initDataBinding(binding: BINDING) {
        binding.setVariable(BR.vm, viewModel)
        this.binding = binding
    }

    abstract fun inject()

    override fun onEvent(eventId: Int) {
        if (eventId == EVENT_BACK) {
            back()
        }
    }
}